package online.longzipeng.back.controller;

import cn.hutool.core.bean.BeanUtil;
import online.longzipeng.back.pojo.Result;
import online.longzipeng.back.pojo.entity.User;
import online.longzipeng.back.pojo.vo.UserInfoVo;
import online.longzipeng.back.pojo.vo.UserVo;
import online.longzipeng.back.service.UserService;
import online.longzipeng.back.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author lzp
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 检验用户的token是否过期
     *
     * @return
     */
    @GetMapping("/check/login")
    public Result<Integer> checkLogin() {
        try {
            UserUtils.getLoginUser();
        } catch (Exception e) {
            return Result.success(0);
        }
        return Result.success(1);
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<UserInfoVo> login(@RequestBody UserInfoVo userInfo) {
        return Result.success(userService.login(userInfo));
    }

    /**
     * 保存用户信息
     */
    @PostMapping("/save/userInfo")
    public Result<UserInfoVo> saveUserInfo(@RequestBody UserInfoVo userInfo) {
        return Result.success(userService.saveUserInfo(userInfo));
    }

    /**
     * 根据token获取用户的信息
     */
    @GetMapping("/get/userInfo")
    public Result<UserInfoVo> getUserInfo() {
        User loginUser = UserUtils.getLoginUser();
        UserInfoVo userInfo = new UserInfoVo();
        BeanUtil.copyProperties(loginUser, userInfo);
        return Result.success(userInfo);
    }

    /**
     * 通过昵称查询用户列表
     */
    @GetMapping("/search")
    public Result<List<UserVo>> search(String nickName, Long teamId) {
        return Result.success(userService.search(nickName, teamId));
    }
}
